package br.com.cogerh.sidec.util;

import java.io.IOException;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.com.cogerh.sidec.view.UsuarioBean;


public class LoginFilter implements Filter{
private boolean logaut;
	@Override
	public void destroy() {
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		
		if(chain == null && request == null && response == null){
			FacesContext.getCurrentInstance().getExternalContext().redirect("../../login.xhtml");  

		}else{

		UsuarioBean usuarioBean = (UsuarioBean)((HttpServletRequest) request).getSession().getAttribute("usuarioBean");

		
		// Se os campos Forem Brancos                                             //Login for errado
		if ((usuarioBean.getNome() == null || usuarioBean.getSenha() == null) || usuarioBean == null || usuarioBean.isLogin()) {
			String contextPath = ((HttpServletRequest) request).getContextPath();
		
			// Redirect para Login
			((HttpServletResponse) response).sendRedirect(contextPath + "/login.xhtml");
		}else {
			// Permissao para Continuar Filtro
			chain.doFilter(request, response);
		}
	}


	}
	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
		
	}
	
	public void destruir(){
		logaut = true;
	}

	public boolean isLogaut() {
		return logaut;
	}

	public void setLogaut(boolean logaut) {
		this.logaut = logaut;
	}

}
